<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>购物车状态</title>
	</head>
	<body>
		<input type="checkbox" name="" id="selectAll" value="" />全选
		<ul>

		</ul>
		<script type="text/javascript">
			var arr;
			let cartGoods = [{
					goodsname: '小米10',
					price: 5000,
					isChecked: false, //代表是否选中了
				},
				{
					goodsname: '苹果10',
					price: 3000,
					isChecked: false, //代表是否选中了
				}
			];
			var Oul = document.getElementsByTagName("ul")[0];
			var selectAll = document.getElementById("selectAll");
			for (var key in cartGoods) {
				var OLi = document.createElement("li");
				var Oinput = document.createElement("input");
				Oinput.setAttribute("type", "checkbox")
				var Ospan = document.createElement("span");
				var text = document.createTextNode("商品名称:" + cartGoods[key].goodsname + "商品价格：" + cartGoods[key].price);
				Ospan.appendChild(text);
				OLi.appendChild(Oinput);
				OLi.appendChild(Ospan);
				Oul.appendChild(OLi);
			}
			var Oin = Oul.getElementsByTagName("input");
			for (var i = 0; i < Oin.length; i++) {
				Oin[i].index = i;
				Oin[i].onclick = function() {
					cartGoods[this.index].isChecked = this.checked;    //根据点击具体的值进行赋值
					arr = [];
					for (var key in cartGoods) {
						
						if (cartGoods[key].isChecked) {
							arr.push(cartGoods[key].isChecked)
						} else {
							arr.push(cartGoods[key].isChecked)
						}
					}
					console.log(arr)
					var result = arr.every(function(value){
						return value;
					})
					if(result)
					{
						selectAll.checked = true;
					}
					else
					{
						selectAll.checked = false;
					}
				}
				
			}

			//点击全选
			selectAll.onclick = function() {
				arr = [];
				if (selectAll.checked) {
					for (var key in cartGoods) {
						cartGoods[key].isChecked = true;
						arr.push(cartGoods[key].isChecked);
					}

					for (var i = 0; i < Oin.length; i++) {
						Oin[i].checked = true;
					}
				} else {
					for (var key in cartGoods) {
						cartGoods[key].isChecked = false;
						arr.push(cartGoods[key].isChecked);
					}
					for (var i = 0; i < Oin.length; i++) {
						Oin[i].checked = false;
					}
				}

			}
		</script>
	</body>
</html>
